package com.bh.weapp.controller.sysuser.order;

import com.bh.common.annotation.Log;
import com.bh.common.enums.OrderStatus;
import com.bh.common.core.controller.BaseController;
import com.bh.common.core.domain.AjaxResult;
import com.bh.common.core.page.TableDataInfo;
import com.bh.common.enums.BusinessType;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.StringUtils;
import com.bh.extend.domain.JcOrderBarcode;
import com.bh.extend.service.IJcOrderBarcodeService;
import com.bh.ledger.service.IJcLedgerDetailService;
import com.bh.ledger.vo.JcLedgerDetailVo;
import com.bh.order.convert.JcOrderConvert;
import com.bh.order.domain.JcLed;
import com.bh.order.domain.JcOrder;
import com.bh.order.domain.JcOrderProduct;
import com.bh.order.domain.JcOrderTrack;
import com.bh.order.dto.JcOrderQueryDto;
import com.bh.order.service.IJcLedService;
import com.bh.order.service.IJcOrderProductService;
import com.bh.order.service.IJcOrderService;
import com.bh.order.service.IJcOrderTrackService;
import com.bh.order.vo.*;
import com.bh.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 订单Controller
 *
 * @author slx
 * @date 2023-04-22
 */
@Api(tags = {"SYS管理员订单API"})
@RestController
@RequestMapping("/api/sysuser/order")
public class JcOrderSysApiController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IJcOrderService jcOrderService;
    @Autowired
    private IJcLedService jcLedService;
    @Autowired
    private IJcLedgerDetailService jcLedgerDetailService;
    @Autowired
    private IJcOrderTrackService jcOrderTrackService;
    @Autowired
    private IJcOrderProductService jcOrderProductService;
    @Autowired
    private IJcOrderBarcodeService jcOrderBarcodeService;
    @Autowired
    private JcOrderConvert jcOrderConvert;
    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @PreAuthorize("@ss.hasPermi('api:order:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(JcOrderQueryDto queryVo) {
        startPage();
        // 默认只查询最近10天的数据
        Map<String, Object> params = queryVo.getParams();
        if (params.get("beginTime") == null || params.get("endTime") == null) {
            params.put("beginTime", DateUtils.formatDate(DateUtils.addDays(DateUtils.getNowDate(), -10)));
            params.put("endTime", DateUtils.getDate());
        }

        //会直接查询出发和到达的机构
        queryVo.setJcOrganizationId(getOrgId());
        List<JcOrderSysApiVO> list = jcOrderService.selectJcOrderSysApiVoList(queryVo);
        return getDataTable(list);
    }

    /**
     * 新增保存订单
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("新增保存订单")
    @PreAuthorize("@ss.hasPermi('api:order:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addSave(@RequestBody JcOrderAddVo addVo) {
        JcOrder jcOrder = jcOrderConvert.toDO(addVo);
        return toAjax(jcOrderService.insertJcOrder(jcOrder));
    }


    /**
     * 新增保存订单, 目前还没有使用
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("确认订单")
    @PreAuthorize("@ss.hasPermi('api:order:order:confirm')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/confirm/{ids}")
    public AjaxResult confirmSave(@PathVariable("ids") String[] ids) {
        return toAjax(jcOrderService.confirmOrderSave(ids));
    }

    /**
     * 修改订单
     */
    @ApiOperation("普通情况获取订单详情")
    @PreAuthorize("@ss.hasPermi('api:order:order:info')")
    @GetMapping("/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        JcOrder jcOrder = jcOrderService.selectJcOrderById(id);
        return AjaxResult.success(jcOrder);
    }

    /**
     * 修改保存订单
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("修改保存订单")
    @PreAuthorize("@ss.hasPermi('api:order:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult editSave(@RequestBody JcOrder jcOrder) {
        return toAjax(jcOrderService.updateJcOrder(jcOrder));
    }


    /**
     * 派送员扫码订单详情(区别在于返回的内容不一致，此处返回内容主要作用是用于查看用户当前订单的数量、货品、地址、新增上楼费等作用)
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("派送员扫码订单详情")
    @PreAuthorize("@ss.hasPermi('api:order:delivery:info')")
    @GetMapping("/deliveryOrderInfoByScan/{code}")
    public AjaxResult deliveryOrderInfoByScan(@PathVariable("code") String code) {
        JcOrderBarcode jcOrderBarcode = jcOrderBarcodeService.selectJcOrderBarcodeByProductCode(code);
        if (jcOrderBarcode == null) {
            //通过订单号码查询
            JcOrder jcOrder = jcOrderService.selectJcOrderByCode(code);
            if (jcOrder == null) {
                return error("未找到扫码订单!");
            }
            jcOrderBarcode = jcOrderBarcodeService.selectJcOrderBarcodeListByOrderId(jcOrder.getId()).get(0);
        }
        JsOrderToAndReceiveVo jcOrder = jcOrderService.selectToAndReceiveVoById(jcOrderBarcode.getOrderId());
        if (jcOrder != null) {
            JcDeliveryOrderVo deliveryOrderVo = jcOrderConvert.toDeliveryOrderVo(jcOrder);
            // 可以查询所有分段订单，但是禁止未到达的订单签收
            List<JcLed> leds = jcLedService.selectDeliverJcLedsByOrderId(jcOrderBarcode.getOrderId());
            deliveryOrderVo.setLeds(leds);
            List<JcLedgerDetailVo> ledgers = jcLedgerDetailService.selectJcLedgerDetailVoListByOrderId(jcOrderBarcode.getOrderId());
            deliveryOrderVo.setLedgers(ledgers);
            deliveryOrderVo.setCurrentLedId(jcOrderBarcode.getLedOrderId());
            if (StringUtils.isNotBlank(jcOrder.getQsPerson())) {
                deliveryOrderVo.setQsPerson(sysUserService.selectUserNickNameByIdOrUserName(jcOrder.getQsPerson()));
            }

            return AjaxResult.success(deliveryOrderVo);
        }
        return error("未找到扫码订单!");
    }


    /**
     * 查询订单追踪列表
     */
    @PreAuthorize("@ss.hasPermi('api:order:track')")
    @ApiOperation("SYS内部查询订单追踪列表")
    @GetMapping("/orderTrack/{jcOrderId}")
    public AjaxResult orderTrack(@PathVariable Long jcOrderId) {
        JcOrderTrack jcOrderTrack = new JcOrderTrack();
        jcOrderTrack.setJcOrderId(jcOrderId);
        List<JcOrderTrack> list = jcOrderTrackService.selectJcOrderTrackList(jcOrderTrack);
        return AjaxResult.success(list);
    }

    /**
     * 查询订单货品明细列表
     */
    @ApiOperation("查询订单货品明细列表")
    @PreAuthorize("@ss.hasPermi('api:order:orderProduct:list')")
    @PostMapping("/orderProductList")
    public AjaxResult orderProductList(@RequestBody JcOrderProduct jcOrderProduct) {
        if (StringUtils.isEmpty((jcOrderProduct.getJcOrderId()))) {
            return error();
        }
        List<JcOrderProduct> list = jcOrderProductService.selectJcOrderProductList(jcOrderProduct);
        return AjaxResult.success(list);
    }


    /**
     * 修改保存订单货品明细
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("新增保存订单货品明细")
    @PreAuthorize("@ss.hasPermi('api:order:orderProduct:add')")
    @Log(title = "订单货品明细", businessType = BusinessType.UPDATE)
    @PostMapping("/addOrderProduct")
    public AjaxResult addOrderProduct(@RequestBody JcOrderProduct jcOrderProduct) {
        if (StringUtils.isEmpty((jcOrderProduct.getJcOrderId()))) {
            return error();
        }
        JcOrder jcOrder = jcOrderService.selectJcOrderById(jcOrderProduct.getJcOrderId());
        if (jcOrder.getStatus() != OrderStatus.ACTIVE.getValue()) {
            return error("禁止修改！");
        }
        return toAjax(jcOrderProductService.insertJcOrderProduct(jcOrderProduct, jcOrder.getJcCustomerId()));
    }

    /**
     * 修改保存订单货品明细
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("修改保存订单货品明细")
    @PreAuthorize("@ss.hasPermi('api:order:orderProduct:edit')")
    @Log(title = "订单货品明细", businessType = BusinessType.UPDATE)
    @PostMapping("/editOrderProduct")
    public AjaxResult editOrderProductSave(@RequestBody JcOrderProduct jcOrderProduct) {
        if (StringUtils.isEmpty((jcOrderProduct.getJcOrderId()))) {
            return error();
        }
        JcOrder jcOrder = jcOrderService.selectJcOrderById(jcOrderProduct.getJcOrderId());
        if (jcOrder.getStatus() != OrderStatus.ACTIVE.getValue()) {
            return error("禁止修改！");
        }
        return toAjax(jcOrderProductService.updateJcOrderProduct(jcOrderProduct));
    }

    /**
     * 删除订单货品明细
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("删除订单货品明细")
    @PreAuthorize("@ss.hasPermi('api:order:orderProduct:remove')")
    @Log(title = "订单货品明细", businessType = BusinessType.DELETE)
    @PostMapping("/removeOrderProduct")
    public AjaxResult removeOrderProduct(Long[] ids) {
        return toAjax(jcOrderProductService.deleteJcOrderProductByIds(ids));
    }
}
